package com.ma.gulimall.product.service.impl;

import com.alibaba.fastjson.TypeReference;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ma.gulimall.constant.ProductConstant;
import com.ma.gulimall.es.SkuEsModel;
import com.ma.gulimall.product.dao.SpuInfoDao;
import com.ma.gulimall.product.entity.*;
import com.ma.gulimall.product.feign.CouponFeignService;
import com.ma.gulimall.product.feign.SearchFeignService;
import com.ma.gulimall.product.feign.WareFeignService;
import com.ma.gulimall.product.service.*;
import com.ma.gulimall.product.vo.*;
import com.ma.gulimall.to.SkuHasStockVo;
import com.ma.gulimall.to.SkuReductionTo;
import com.ma.gulimall.to.SpuBoundTo;
import com.ma.gulimall.utils.PageUtils;
import com.ma.gulimall.utils.Query;
import com.ma.gulimall.utils.R;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoDao, SpuInfoEntity> implements SpuInfoService {

    @Autowired
    SpuInfoService spuInfoService;

    @Autowired
    SpuInfoDescService spuInfoDescService;

    @Autowired
    SpuImagesService spuImagesService;

    @Autowired
    AttrService attrService;


    @Autowired
    ProductAttrValueService productAttrValueService;

    @Autowired
    SkuInfoService skuInfoService;

    @Autowired
    SkuImagesService skuImagesService;

    @Autowired
    SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    CouponFeignService couponFeignService;

    @Autowired
    BrandService brandService;

    @Autowired
    CategoryService categoryService;

    @Autowired
    WareFeignService wareFeignService;

    @Autowired
    SearchFeignService searchFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfoEntity> page = this.page(
                new Query<SpuInfoEntity>().getPage(params),
                new QueryWrapper<SpuInfoEntity>()
        );

        return new PageUtils(page);
    }

    /**
     * 19、新增商品
     * /product/spuinfo/save
     * 新增商品，保存关联的很多信息
     * // TODO: 2021/8/26 高级篇部分完善事务回滚等
     * // TODO: 2021/11/9 后台管理系统，底并发 适合用 Seata AT做分布式事务  --> @GlobalTransactional
     */

    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo vo) {

        //1、保存spu基本信息   表`pms_spu_info`  实体类SpuInfoEntity
        SpuInfoEntity spuInfoEntity = new SpuInfoEntity();
        BeanUtils.copyProperties(vo, spuInfoEntity);
        spuInfoEntity.setCreateTime(new Date());
        spuInfoEntity.setUpdateTime(new Date());
        this.saveBaseSpuInfo(spuInfoEntity);

        //2、保存spu的描述图片 表`pms_spu_info_desc` 实体类SpuInfoDescEntity
        List<String> decript = vo.getDecript();
        SpuInfoDescEntity spuInfoDescEntity = new SpuInfoDescEntity();
        spuInfoDescEntity.setSpuId(spuInfoEntity.getId());
        spuInfoDescEntity.setDecript(String.join(",", decript));
        spuInfoDescService.saveSpuInfoDesc(spuInfoDescEntity);

        //3、保存spu的图片集 表`pms_spu_images` 实体类SpuImagesEntity
        List<String> images = vo.getImages();
        spuImagesService.saveImages(spuInfoEntity.getId(), images);

        //4、保存spu的规格参数 表`pms_product_attr_value` 实体类ProductAttrValueEntity
        List<BaseAttrs> baseAttrs = vo.getBaseAttrs();
        List<ProductAttrValueEntity> collect = baseAttrs.stream().map(attr -> {
            ProductAttrValueEntity valueEntity = new ProductAttrValueEntity();

            //先对baseattrs中有的进行拷贝
            valueEntity.setSpuId(spuInfoEntity.getId());
            valueEntity.setAttrValue(attr.getAttrValues());
            valueEntity.setQuickShow(attr.getShowDesc());
            valueEntity.setAttrId(attr.getAttrId());
            //还需要attr_name   需要从 表`pms_attr` 实体类AttrEntity中查
            AttrEntity byId = attrService.getById(attr.getAttrId());
            valueEntity.setAttrName(byId.getAttrName());
            return valueEntity;
        }).collect(Collectors.toList());

        productAttrValueService.saveProductAttr(collect);


        //5、保存spu的积分信息 跨服务保存-->库gulimall-sms 表`sms_spu_bounds`
        Bounds bounds = vo.getBounds();
        /**
         * TO(Transfer Object),不同微服务之间的数据传输对象
         * */
        SpuBoundTo spuBoundTo = new SpuBoundTo();
        BeanUtils.copyProperties(bounds, spuBoundTo);
        spuBoundTo.setSpuId(spuInfoEntity.getId());
        R r = couponFeignService.saveSpuBounds(spuBoundTo);
        if (r.getCode() != 0) {
            log.error("远程保存SKU积分信息失败");
        }


        //6、保存当前spu对应的所有sku信息：表`pms_sku_info`
        List<Skus> skus = vo.getSkus();
        if (skus != null && skus.size() > 0) {
            //多个sku 用foreach遍历得到
            skus.forEach(item -> {
                //找到默认图片，如果未设置，默认为空字符串
                String defaultImg = "";
                for (Images image : item.getImages()) {
                    if (image.getDefaultImg() == 1) {
                        defaultImg = image.getImgUrl();
                    }
                }
                //6.1）、sku基本信息  表`pms_sku_info`    实体类SkuInfoEntity
                SkuInfoEntity skuInfoEntity = new SkuInfoEntity();
                /**
                 * 对skus中有（1、sku名称 2、标题	3、副标题 4、价格）经行对应拷贝
                 * 	不包含（1、sku的id [自增字段，不用设置]
                 * 	2、所属spu的Id	3、sku介绍描述  4、sku所属分类id
                 * 	5、sku所属品牌id  6、默认图片 7、销量）的信息进行查询嵌入或设置默认值
                 *    */
                BeanUtils.copyProperties(item, skuInfoEntity);
                skuInfoEntity.setSpuId(spuInfoEntity.getId());
                skuInfoEntity.setCatalogId(spuInfoEntity.getCatalogId());
                skuInfoEntity.setBrandId(spuInfoEntity.getBrandId());
                skuInfoEntity.setSkuDefaultImg(defaultImg);
                skuInfoEntity.setSaleCount(0L);
                skuInfoService.saveSkuInfo(skuInfoEntity);

                //6.2）、sku的图片信息 表`pms_sku_images`
                /**
                 * Skus-->item 存放 List<Images> images，流式编程获得
                 *     private String imgUrl;
                 *     private int defaultImg;
                 *  此外SkuImagesEntity还需要设置sku_id
                 *  特别注意为空时不返回信息
                 *  // TODO: 2021/8/26  没有图片路径的不保存 通过 filter() 已实现
                 * */
                Long skuId = skuInfoEntity.getSkuId();
                List<SkuImagesEntity> imagesEntities = item.getImages().stream().map(img -> {
                    SkuImagesEntity skuImagesEntity = new SkuImagesEntity();
                    skuImagesEntity.setSkuId(skuId);
                    skuImagesEntity.setImgUrl(img.getImgUrl());
                    skuImagesEntity.setDefaultImg(img.getDefaultImg());
                    return skuImagesEntity;

                }).filter(entity -> {
                    return !StringUtils.isEmpty(entity.getImgUrl());
                }).collect(Collectors.toList());
                skuImagesService.saveBatch(imagesEntities);

                //6.3）、sku的销售属性信息  表`pms_sku_sale_attr_value` 实体类SkuSaleAttrValueEntity
                /**
                 *  Skus中的 List<Attr> attr 包含
                 *     private Long attrId;
                 *     private String attrName;
                 *     private String attrValue;
                 *  此外  实体类SkuSaleAttrValueEntity 还需要 skuId
                 * */
                List<Attr> attr = item.getAttr();
                List<SkuSaleAttrValueEntity> skuSaleAttrValueEntities = attr.stream().map(a -> {
                    SkuSaleAttrValueEntity skuSaleAttrValueEntity = new SkuSaleAttrValueEntity();
                    BeanUtils.copyProperties(a, skuSaleAttrValueEntity);
                    skuSaleAttrValueEntity.setSkuId(skuId);
                    return skuSaleAttrValueEntity;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(skuSaleAttrValueEntities);

                //6.4）、sku的优惠，满减信息   库gulimall-sms  -->表
                //`sms_member_price` `sms_sku_ladder` `sms_sku_full_reduction`
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(item, skuReductionTo);
                skuReductionTo.setSkuId(skuId);
                if (skuReductionTo.getFullCount() > 0 || skuReductionTo.getFullPrice().compareTo(BigDecimal.ZERO) == 1) {
                    R r1 = couponFeignService.saveSkuReduction(skuReductionTo);
                    if (r1.getCode() != 1) {
                        log.error("远程保存SKU积分信息失败");
                    }
                }
            });
        }
    }

    @Override
    public void saveBaseSpuInfo(SpuInfoEntity spuInfoEntity) {
        this.baseMapper.insert(spuInfoEntity);
    }

    /**
     * 18、spu检索      GET /product/spuinfo/list
     * 请求参数主要有 params:
     * page: 1,//当前页码
     * limit: 10,//每页记录数
     * sidx: 'id',//排序字段
     * order: 'asc/desc',//排序方式
     * key: '华为',//检索关键字
     * catelogId: 6,//三级分类id
     * brandId: 1,//品牌id
     * status: 0,//商品状态
     */
    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {

        QueryWrapper<SpuInfoEntity> queryWrapper = new QueryWrapper<>();

        String key = (String) params.get("key");
        if (!StringUtils.isEmpty(key)) {
            queryWrapper.and((wrapper) -> {
                wrapper.eq("id", key).or().like("spu_name", key);
            });
        }

        String status = (String) params.get("status");
        if (!StringUtils.isEmpty(status)) {
            queryWrapper.eq("publish_status", status);
        }

        String brandId = (String) params.get("brandId");
        if (!StringUtils.isEmpty(brandId) && !"0".equalsIgnoreCase(brandId)) {
            queryWrapper.eq("brand_id", brandId);
        }

        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty(catelogId) && !"0".equalsIgnoreCase(catelogId)) {
            queryWrapper.eq("catalog_id", catelogId);
        }
        IPage<SpuInfoEntity> page = this.page(new Query<SpuInfoEntity>().getPage(params), queryWrapper);


        return new PageUtils(page);
    }

    /**
     * 分布式 高级篇 130p  ~  135p  --> 商品上架功能
     * 传入spu_id
     * 一、检索属性的设
     * 1、首先查出当前spu对应的所有sku信息SkuInfoEntity  因为前端点击上架是选中的是spu，需要上架的是对应的所有sku
     * 2、去`pms_product_attr_value`表中查到该spu对应的所有基本属性baseAttrs，收集属性id---》attrIds
     * 3、过滤掉可检索的属性id，得到searchAttrIds
     * 4、将可检索的属性的一些值拷贝到SkuEsModel.Attrs中
     * 二、查询sku的库存
     * 1、将skus中的skuid收集为List<Long> skuIdList
     * 2、将skuIdList发送给远程接口，查询是否有库存
     * 3、将查询到结果用TypeReference<List<SkuHasStockVo>> 封装
     * 4、库存信息最终封装到Map<Long, Boolean> finalStockMap中
     * <p>
     * 三、封装上架服务需要的数据SkuEsModel也即要存放到es中的数据
     * 1、将在sku中查到的数据一一对应封装到SkuEsModel中
     * 2、返回List<SkuEsModel> upProducts 封装号的数据
     * 四、将封装好的数据做上架，也即PUT到es中
     * 1、远程调用，批量上传，上传错误返回错误提示
     * 五、上架成功，修改当前spu的状态，状态码与更新时间
     * pms_spu_info 的   publish_status
     */
    @Override
    public void up(Long spuId) {

        //1、查出当前spuId对应的所有sku的信息，品牌的名字
        List<SkuInfoEntity> skus = skuInfoService.getSkusBySpuId(spuId);

        // TODO: 2021/9/7 4、查询当前sku的所有可以被用来检索的规格属性
        List<ProductAttrValueEntity> baseAttrs = productAttrValueService.baseAttrlistforspu(spuId);
        List<Long> attrIds = baseAttrs.stream().map(attr -> {
            return attr.getAttrId();
        }).collect(Collectors.toList());
        List<Long> searchAttrIds = attrService.selectSearchAttrs(attrIds);
        Set<Long> idSet = new HashSet<>(searchAttrIds);

        List<SkuEsModel.Attrs> attrsList = baseAttrs.stream
                ().filter(item -> {
            return idSet.contains(item.getAttrId());
        }).map(item -> {
            SkuEsModel.Attrs attrs = new SkuEsModel.Attrs();
            BeanUtils.copyProperties(item, attrs);
            return attrs;
        }).collect(Collectors.toList());

        List<Long> skuIdList = skus.stream().map(SkuInfoEntity::getSkuId).collect(Collectors.toList());
        // TODO: 2021/9/7 1、发送远程调用，库存系统查询是否有库存
        Map<Long, Boolean> stockMap = null;
        try {
            R skusHasStock = wareFeignService.getSkusHasStock(skuIdList);
            TypeReference<List<SkuHasStockVo>> typeReference = new TypeReference<List<SkuHasStockVo>>() {
            };
            stockMap = skusHasStock.getData(typeReference).stream()
                    .collect(Collectors.toMap(SkuHasStockVo::getSkuId, item -> item.getHasStock()));
        } catch (Exception e) {
            log.error("库存服务查询异常:原因{}", e);
        }

        //2、封装每个sku的信息封装每个sku的信息
        Map<Long, Boolean> finalStockMap = stockMap;
        List<SkuEsModel> upProducts = skus.stream().map(sku -> {
            SkuEsModel esModel = new SkuEsModel();
            //组装需要的数据  命名相同直接对拷copyProperties，命名不同set进去，没有的需要查出来
            esModel.setSkuPrice(sku.getPrice());
            esModel.setSkuImg(sku.getSkuDefaultImg());

            //设置库存信息
            if (finalStockMap == null) {
                esModel.setHasStock(true);
            } else {
                esModel.setHasStock(finalStockMap.get(sku.getSkuId()));
            }

            // TODO: 2021/9/7 2、热度评分 0
            esModel.setHotScore(0L);
            // TODO: 2021/9/7 3、查询品牌和分类的信息
            BrandEntity brandEntity = brandService.getById(sku.getBrandId());
            esModel.setBrandId(brandEntity.getBrandId());
            esModel.setBrandName(brandEntity.getName());
            esModel.setBrandImg(brandEntity.getLogo());
            CategoryEntity categoryEntity = categoryService.getById(sku.getCatalogId());
            esModel.setCatalogId(categoryEntity.getCatId());
            esModel.setCatalogName(categoryEntity.getName());
            BeanUtils.copyProperties(sku, esModel);
            //设置检索属性
            esModel.setAttrs(attrsList);

            return esModel;
        }).collect(Collectors.toList());

        // TODO: 2021/9/7 5、将数据发送给es进行保存：gulimall-search
        R r = searchFeignService.productStatusUp(upProducts);

        if (r.getCode() == 0) {
            //远程调用成功
            // TODO: 2021/9/11 6、修改当前spu的状态
            this.baseMapper.updateSpuStatus(spuId, ProductConstant.ProductStatusEnum.SPU_UP.getCode());
        } else {
            //远程调用失败
            // TODO: 2021/9/11  7、重复调用？ 接口幂等性：重试机制
            /**
             * Feign的调用流程
             * 1、构造请求数据，将对象转换为json
             * 2、发送请求并执行（执行成功会解码响应数据
             * 3、执行请求会有重试机制
             * */
        }
    }

    @Override
    public SpuInfoEntity getSpuInfoBySkuId(Long skuId) {
        SkuInfoEntity byId = skuInfoService.getById(skuId);
        Long spuId = byId.getSpuId();
        return getById(spuId);

    }

}












